package com.batch.adance.xml;
import java.util.HashMap;
import java.util.Map;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;

//@Configuration
public class XMLFileDemoJobConfiguration {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    @Qualifier("XMLFileWriterDemo")
    private ItemWriter<? super WeatherData> XMLFileWriterDemo;

    @Bean
    public Job XMLFileDemoReaderJobTwo() {
        return jobBuilderFactory.get("XMLFileDemoReaderJobTwo")
                .start(XMLFileDemoReaderStepTwo())
                .build();

    }

    @Bean
    public Step XMLFileDemoReaderStepTwo() {
        return stepBuilderFactory.get("XMLFileDemoReaderStepTwo")
                .<WeatherData,WeatherData>chunk(2)
                .reader(XMLFileItemReader())
                .writer(XMLFileWriterDemo)
                .build();
    }

    @Bean
    @StepScope
    public StaxEventItemReader<WeatherData> XMLFileItemReader() {
        StaxEventItemReader<WeatherData> reader=new StaxEventItemReader<WeatherData>();
        reader.setResource(new ClassPathResource("weather.xml"));
        reader.setFragmentRootElementName("data");
        XStreamMarshaller unmarshaller=new XStreamMarshaller();
        Map<String,Class> map=new HashMap<>();
        map.put("data", WeatherData.class);
        unmarshaller.setAliases(map);
        reader.setUnmarshaller(unmarshaller);//序列化
        return reader;

    }

}